<?php

class Application_Model_LogementMapper
{
	protected $_dbTable;
	
	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}
	
	public function getDbTable()
	{
		if (null === $this->_dbTable) {
			$this->setDbTable('Application_Model_DbTable_Logement');
		}
		return $this->_dbTable;
	}
	
	public function save(Application_Model_Logement $log)
	{
		$data = array(
				'nomcourtlog'   => $log->getNomCourt(),
				'numero' => $log->getNumero(),
				'superficie' => $log->getSuperficie(),
				'typelog' => $log->getTypeLogement(),
				'etage' => $log->getEtage(),
				'notelog' => $log->getNoteLogement(),
		);
	
		if (null === ($id = $log->getId())) {
			unset($data['idlogement']);
			$this->getDbTable()->insert($data);
		} else {
			$this->getDbTable()->update($data, array('idlogement = ?' => $id));
		}
	}
	
	public function find($id, Application_Model_Logement $log)
	{
		$result = $this->getDbTable()->find($id);
		if (0 == count($result)) {
			return;
		}
		$row = $result->current();
		$log->setId($row->idutilisateur)
			->setNomCourt($row->nomcourtlog)
			->setNumero($row->numero)
			->setSuperficie($row->superficie)
			->setTypeLogement($row->typelog)
			->setEtage($row->etage)
			->setNoteLogement($row->notelog);
	}
	
	public function fetchAll()
	{
		$resultSet = $this->getDbTable()->fetchAll();
		$entries   = array();
		foreach ($resultSet as $row) {
			$entry = new Application_Model_Utilisateur();
			$entry->setId($row->idutilisateur)
				->setNomCourt($row->nomcourtlog)
				->setNumero($row->numero)
				->setSuperficie($row->superficie)
				->setTypeLogement($row->typelog)
				->setEtage($row->etage)
				->setNoteLogement($row->notelog);
			$entries[] = $entry;
		}
		return $entries;
	}

}

